import app from '../app';


export const mergeOf = (...arg) => {
    return Object.assign({}, ...arg);
}

export const oneOf = (val, arr) => {
    return arr.includes(val);
};

export const cloneOf = (val) => {
    return JSON.parse(JSON.stringify(val));
};

export const idToArray = (ids) => {
    let arr = [];

    if (isNumeric(ids)) {
        arr = [ parseInt(ids) ];
    }
    else if (typeof ids === 'string') {
        arr = ids.split(',').map((each) => parseInt(each));
    }
    return arr;
};

export const isNumeric = (n) => {
    return !isNaN(parseFloat(n)) && isFinite(n);
}


export const flattenDeep = (arr1) => {
    return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

const defaultNotify                = {
    title                   : '成功',
    message                 : '操作成功',
    type                    : 'success',
    duration                : 1000,
    dangerouslyUseHTMLString: true,
};
export const filterResponseMessage = (message, title = '错误') => {
    let type = typeof message;
    if (type === 'string') {
        message = [ message ];
    }
    else if (type === 'object') {
        message = flattenDeep(Object.values(message || {}));
    }

    let len = message.length;

    return mergeOf(defaultNotify, {
        title,
        message : message.join('<br/>'),
        duration: len ? len * 1000 : 1000,
    })
};

export const responseNotify = (res, success = {}) => {
    let { data, result } = res;
    if (result) {
        app.$notify(mergeOf(defaultNotify, success));
    }
    else if (data) {
        let message = filterResponseMessage(data.message);

        if (data.code === 0 || data.code === 400) {
            app.$notify.error(message);
        }
        else {
            app.$notify.error(message);
        }
    }
};
